Ex004, ListBox
ListBox is a common windows control, it used at many windows applications, even
this Electronic Book program contains List Box !. Look at left side of this form
you will find a list of items, that is Delphi's ListBox.
List box is used to show list of string items and enables user to select item or
group of items.
Exercise 004: ListBox
1. Drop a ListBox from standard page.
2. Drop an Edit box and name it edName
3. Drop a Label and name it laName
4. Drop a Button and caption it Add
5. At button's OnClick event write this code:
ListBox1.Items.Add(edName.Text);
6. Drop another Button and caption it Delete
7. At second button's OnClick event write:
if ListBox1.ItemIndex <> -1 then
ListBox1.Items.Delete(ListBox1.ItemIndex);
Instead of the above code in which ListBox1 was repeted, you can write at second
button's OnClick event:
with ListBox1 do
if ItemIndex <> -1 then
Items.Delete(ItemIndex);
8. Drop another Button and write on it's caption 'Clear'
9. At third button's OnClick event write:
ListBox1.Items.Clear;
10. At ListBox1 OnClick event write:
laName.Caption:= ListBox1.Items[ListBox1.ItemIndex];
11. Run the program, enter names on edit box then press add, click on list items
to see what will happened.
If you want to store ListBox contents in every time your program starts, follow
below steps:
12. At form's OnClose event write this code:
ListBox1.Items.SaveToFile(
ChangeFileExt(ParamStr(0), '.ini'));
13. At form's OnCreate event write:
if FileExists(ChangeFileExt(ParamStr(0)), '.ini') then
ListBox1.Items.LoadFromFile(
ChangeFileExt(ParamStr(0), '.ini'));
Notes:
- TListBox contains Items object in which the actual list data stored. Items can
be used as array of string such as:
laName.Caption:= ListBox1.Items[0]; { First Item in the list }
ListBox1.Items[1]:= 'Second item';
Items is a TStringList object, the main methods of TStringList are:
Add: add new item at the end of list
Delete: remove item from the list
Clear: remove all items from the list
IndexOf: search for specific item in the list
LoadFromFile: load string items from text file
SaveToFile: save items into a text file
- ListBox's ItemIndex property points to selected item in the list.
See also:
TStringList